package com.sun.example.recyclerview;

import android.view.View;
import android.view.ViewGroup;

import androidx.recyclerview.widget.RecyclerView;

/**
 * @author tianxiaolong
 * time：2019-10-04 17:01
 * description：
 */
public class TestLayoutManager extends RecyclerView.LayoutManager {


	/**
	 * 返回默认的layoutParams
	 * @return
	 */
	@Override
	public RecyclerView.LayoutParams generateDefaultLayoutParams() {
		return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
	}

	/**
	 * 类似于viewgroup的layout方法
	 * @param recycler
	 * @param state
	 */
	@Override
	public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
		if(getItemCount()==0)return;
		if(state.isPreLayout())return;
		//在布局之前，将所有的子View先Detach掉，放入到Scrap缓存中
		detachAndScrapAttachedViews(recycler);
		int offset = 0;
		final int  itemCount  = getItemCount();
		for (int i=0;i<itemCount;i++){

			final View itemView = recycler.getViewForPosition(i);
			addView(itemView);
measureChildWithMargins(itemView,0,0);
			int width = getDecoratedMeasuredWidth(itemView);
			int height = getDecoratedMeasuredHeight(itemView);
			int left = (getWidth() - width)/2;

			layoutDecorated(itemView,left,offset,getWidth() - left,offset + height);
			offset+=height;
            totalHeight+=height;
		}

	}

	@Override
	public boolean canScrollVertically() {
		return true;
	}

	private int totalHeight = 0;
	private int verticalScrollOffset = 0;
	@Override
	public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
		int travel = dy;
		//如果滑动到最顶部
		if(verticalScrollOffset+dy < 0){
			travel = -verticalScrollOffset;
			//如果滑动到底部
		}else if(verticalScrollOffset+dy > totalHeight - getVerticalSpace()){
			travel = totalHeight - getVerticalSpace() - verticalScrollOffset;
		}
		verticalScrollOffset +=travel;
		offsetChildrenVertical(-travel);
		return travel;
	}

	/**
	 * 获取RecyclerView在垂直方向上的可用空间，即去除了padding后的高度
	 *
	 * @return
	 */
	private int getVerticalSpace() {
		return getHeight() - getPaddingBottom() - getPaddingTop();
	}
}
